package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessTypeErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.listbatch.pojo.dto.CancelDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductSerialBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseInvoiceEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.business.SerialStatusEnum;
import com.xbongbong.saas.enums.dictionary.IsCancelEnum;
import com.xbongbong.saas.enums.dictionary.IsRedEnum;
import com.xbongbong.saas.enums.product.PurchaseProductEnum;
import com.xbongbong.saas.enums.product.ReturnPurchaseProductEnum;
import com.xbongbong.saas.model.ProductSerialBalanceModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.ReturnedPurchaseInvoiceModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.service.ListBatchService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.util.ProductUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class ReturnPurchaseHelp {

    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private SaasProductHelp saasProductHelp;
    @Resource
    private ProductSerialBalanceModel productSerialBalanceModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private ListBatchService listBatchService;
    @Resource
    private ReturnedPurchaseInvoiceModel returnedPurchaseInvoiceModel;


    /**
     * 更新退货单产品
     *
     * @param returnedPurchaseEntityExt     前端传入的数据
     * @author Jian.Wang
     * @date  2019/2/21 22:01
     */
    public Map<Long, Double> setReturnedPurchaseProducts(PaasFormDataEntity returnedPurchaseEntityExt) throws XbbException {
        String corpid = returnedPurchaseEntityExt.getCorpid();
        Long dataId = returnedPurchaseEntityExt.getId();
        JSONObject returnedPurchaseData = returnedPurchaseEntityExt.getData();
        JSONArray productArray = returnedPurchaseData.getJSONArray(ReturnedPurchaseEnum.PRODUCTS.getAttr());
        // 产品数据留个副本，给序列号用
        List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntityList = returnedPurchaseProductModel.getProductsByRetPurchaseId(corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        Map<Long, ReturnedPurchaseProductEntity> originProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (ReturnedPurchaseProductEntity returnedPurchaseProductEntity : returnedPurchaseProductEntityList) {
            originProductMap.put(returnedPurchaseProductEntity.getId(), returnedPurchaseProductEntity);

        }
        List<ReturnedPurchaseProductEntity> productAddList = new ArrayList<>();
        List<ReturnedPurchaseProductEntity> productUpdateList = new ArrayList<>();
        Map<Integer, ReturnedPurchaseProductEntity> returnedPurchaseProductMap = new HashMap<>(productArray.size());
        Map<Integer, JSONObject> seqMap = new HashMap<>(productArray.size());
        Map<Long, PaasFormDataEntityExt> productMap = saasProductHelp.product2saveMap(corpid,productArray);
        Integer sort = 0;
        Map<Long, Double> changeNumMap = new HashMap<>(productArray.size());
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject jsonObject = productArray.getJSONObject(i);
            JSONArray seqArray = jsonObject.getJSONArray(ProductConstant.SEQ);
            int enableSerialNumber = jsonObject.getIntValue(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr());
            // 移除序列号相关数据，不存入关联产品数据中
            jsonObject.remove(ProductConstant.SEQ);
            jsonObject.remove(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr());
            jsonObject.remove(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr());

            Long pageProductId = jsonObject.getLong(ReturnPurchaseProductEnum.PRODUCT.getAttr());
            Long businessProductId = jsonObject.getLong(BusinessConstant.PRODUCT_SUB_ID);
            Double productNum = jsonObject.getDouble(ReturnPurchaseProductEnum.NUM.getAttr());
//            String memo = jsonObject.getString(ReturnPurchaseProductEnum.MEMO.getAttr());
            boolean addProductFlag = businessProductId == null || businessProductId.equals(0L) || businessProductId < 0L;
            ReturnedPurchaseProductEntity returnedPurchaseProductEntity;
            Double originNum = 0D;
            if (addProductFlag) {
                //新增产品
                returnedPurchaseProductEntity = new ReturnedPurchaseProductEntity();
                productAddList.add(returnedPurchaseProductEntity);
            } else if (originProductMap.containsKey(businessProductId)) {
                //编辑产品
                returnedPurchaseProductEntity = originProductMap.get(businessProductId);
                if (Objects.equals(DelEnum.APPROVE_FAILED.getDel(), returnedPurchaseProductEntity.getDel())) {
                    returnedPurchaseProductEntity.setDel(DelEnum.NORMAL.getDel());
                }
                productUpdateList.add(returnedPurchaseProductEntity);
                originNum = returnedPurchaseProductEntity.getProductNum();
                //只剩删除的产品
                originProductMap.remove(businessProductId);
            } else {
                //删除产品
                continue;
            }
            JSONObject productData = productMap.get(pageProductId).getData();
            Integer enableMultiUnit = productData.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
            if (Objects.equals(enableMultiUnit, 1)) {
                ProductUtil.setBusinessUnit(jsonObject, returnedPurchaseProductEntity);
                returnedPurchaseProductEntity.setProductUnit(jsonObject.getString(SelectProductEnum.UNIT.getAttr()));
            } else {
                returnedPurchaseProductEntity.setProductUnit(productData.getString(ProductEnum.UNIT.getAttr()));
                jsonObject.put(PurchaseProductEnum.UNIT.getAttr(),productData.getString(ProductEnum.UNIT.getAttr()));
            }
            returnedPurchaseProductEntity.setAddTime(DateTimeUtil.getInt());
            returnedPurchaseProductEntity.setUpdateTime(DateTimeUtil.getInt());
            returnedPurchaseProductEntity.setDel(0);
            returnedPurchaseProductEntity.setParentId(productData.getLong(ProductEnum.PARENT_ID.getAttr()));
            returnedPurchaseProductEntity.setProductId(pageProductId);
            returnedPurchaseProductEntity.setProductName(FastJsonHelper.getStringOrDefaultFromFormData(productData, ProductEnum.NAME.getAttr(), ""));
            returnedPurchaseProductEntity.setProductNo(productMap.get(pageProductId).getSerialNo());
            returnedPurchaseProductEntity.setProductSpecification(FastJsonHelper.getStringOrDefaultFromFormData(productData, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), ""));
            String unit = FastJsonHelper.getStringOrDefaultFromFormData(productData, ProductEnum.UNIT.getAttr(), "");
            SaveFormatHelp.formatLinkBusiness4Save(jsonObject, ReturnPurchaseProductEnum.WAREHOUSE.getAttr(),"warehouseName", FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
//            returnedPurchaseProductEntity.setProductUnit(unit);
            returnedPurchaseProductEntity.setProductNum(productNum);
            returnedPurchaseProductEntity.setReturnPurchaseId(dataId);
            returnedPurchaseProductEntity.setCorpid(corpid);
            returnedPurchaseProductEntity.setMoney(Arith.mul(jsonObject.getDouble(ReturnPurchaseProductEnum.PURCHASE_PRICE.getAttr()), productNum));
            returnedPurchaseProductEntity.setProductPrice(jsonObject.getDouble(ReturnPurchaseProductEnum.PURCHASE_PRICE.getAttr()));
            returnedPurchaseProductEntity.setMemo(jsonObject.getString(ReturnPurchaseProductEnum.MEMO.getAttr()));
            returnedPurchaseProductEntity.setSort(sort);
//            jsonObject.put(ReturnedPurchaseOutstockProductEnum.UNIT.getAttr(),unit);
            returnedPurchaseProductEntity.setData(jsonObject);
            if (Objects.nonNull(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID))) {
                returnedPurchaseProductEntity.setRefProductId(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID));
                changeNumMap.put(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID), Arith.sub(productNum, originNum));
            }
            if (addProductFlag) {
                returnedPurchaseProductMap.put(i, returnedPurchaseProductEntity);

                // 新增序列号，关联产品不保存序列号，但是后面序列号保存以及生成出入库单需要序列号数据，所以给他加回去
                if (Objects.nonNull(seqArray) && !seqArray.isEmpty()) {
                    JSONObject seqJson = new JSONObject();
                    seqJson.put(ProductConstant.SEQ, seqArray);
                    seqJson.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), enableSerialNumber);
                    seqMap.put(i, seqJson);
                }
            }
        }

        returnedPurchaseProductModel.insertBatch(productAddList);
        returnedPurchaseProductMap.forEach((i, returnedPurchaseProductEntity)->{
            JSONObject jsonObject = productArray.getJSONObject(i);
            // 工作流里后面需要用到
            jsonObject.put(BusinessConstant.PRODUCT_SUB_ID, returnedPurchaseProductEntity.getId());
            if (seqMap.containsKey(i)) {
                jsonObject.putAll(seqMap.get(i));
            }
        });

        returnedPurchaseProductModel.updateMulti(productUpdateList, corpid);
        List<Long> deleteList = new ArrayList<>();
        for (Map.Entry<Long, ReturnedPurchaseProductEntity> entry : originProductMap.entrySet()) {
            ReturnedPurchaseProductEntity delProduct = entry.getValue();
            changeNumMap.put(delProduct.getRefProductId(), Arith.sub(0D, delProduct.getProductNum()));
            deleteList.add(delProduct.getId());
        }
        returnedPurchaseProductModel.deleteBatch(deleteList, corpid, DelEnum.DELETE.getDel());
        return changeNumMap;
    }

    /**
     * 编辑采购退货单删除的产品序列号处理
     * @param delProduct 删除关联产品
     */
    public void updateSerial(ReturnedPurchaseProductEntity delProduct) throws XbbException {
        productSerialFlowModel.delByRefProductAndBusinessType(delProduct.getCorpid(), delProduct.getId(), XbbRefTypeEnum.RETURNED_PURCHASE.getCode());

        List<ProductSerialBalanceEntity> balanceEntities = productSerialBalanceModel.getByRefProductId(delProduct.getId(), XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), delProduct.getCorpid());
        if (Objects.nonNull(balanceEntities)) {
            for (ProductSerialBalanceEntity entity : balanceEntities) {
                String seqKey = entity.getSeqKey();

                ProductSerialFlowEntity lastSerialFlow = productSerialFlowModel.getLastSerialFlow(delProduct.getCorpid(), seqKey, entity.getRefId());
                entity.setRefId(lastSerialFlow.getRefId());
                entity.setBusinessType(lastSerialFlow.getBusinessType());
                entity.setRefProductId(lastSerialFlow.getRefProductId());
                entity.setAddTime(lastSerialFlow.getAddTime());
                entity.setUpdateTime(lastSerialFlow.getUpdateTime());
                entity.setDate(lastSerialFlow.getDate());
                entity.setWarehouseId(lastSerialFlow.getWarehouseId());
                productSerialBalanceModel.update(entity);
            }
        }
    }


    public void saveSerial(ReturnedPurchaseProductEntity returnedPurchaseProductEntity, Long dataId, String corpid, JSONObject returnedPurchaseData, Map<Long, JSONObject> productMap) throws XbbException {
        JSONObject productData = productMap.get(returnedPurchaseProductEntity.getId());
        if (Objects.isNull(productData)) {
            return;
        }
        List<ProductSerialFlowEntity> productSerialFlowEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, ProductSerialFlowEntity> productSerialFlowEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //
        List<ProductSerialFlowEntity> flowEntityList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), corpid);
        List<String> serialList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionUtils.isNotEmpty(flowEntityList)) {
            flowEntityList.forEach(item -> serialList.add(item.getSeqKey()));
        }
        Set<String> seqKeyList = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        JSONArray seqArray = productData.getJSONArray(ProductConstant.SEQ);
        if (BasicConstant.ZERO.equals(productData.getIntValue(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr())) && (Objects.isNull(seqArray) || seqArray.isEmpty())) {
            return;
        }
        Long productId = productData.getLong(ReturnPurchaseProductEnum.PRODUCT.getAttr());
        for (int j = 0; j < seqArray.size(); j++) {
            JSONObject seqData = seqArray.getJSONObject(j);
            String serial = seqData.getString(SerialEnum.SERIAL.getAttr());
            String seqKey = productId + "_" + serial;
            if (serialList.contains(seqKey)) {
                throw new XbbException(ProductErrorCodeEnum.API_ERROR_205094, String.format(ProductErrorCodeEnum.API_ERROR_205094.getMsg(), serial));
            }
            ProductSerialFlowEntity productSerialFlowEntity = new ProductSerialFlowEntity();
            productSerialFlowEntity.setCorpid(corpid);
            productSerialFlowEntity.setProductId(productId);
            productSerialFlowEntity.setSeq(serial);
            productSerialFlowEntity.setMemo(seqData.getString(SerialEnum.MEMO.getAttr()));
            productSerialFlowEntity.setStatus(SerialStatusEnum.IN_STOCK.getCode());
            productSerialFlowEntity.setDate(DateTimeUtil.getInt());
            productSerialFlowEntity.setBusinessType(XbbRefTypeEnum.RETURNED_PURCHASE.getCode());
            productSerialFlowEntity.setRefId(dataId);
            // 关联产品id
            productSerialFlowEntity.setRefProductId(returnedPurchaseProductEntity.getId());
            productSerialFlowEntity.setRefSheetNo(returnedPurchaseData.getString(FieldTypeEnum.SERIALNO.getAlias()));
            productSerialFlowEntity.setParentId(returnedPurchaseProductEntity.getParentId());

            SaveFormatHelp.formatLinkBusiness4Save(productData, ReturnPurchaseProductEnum.WAREHOUSE.getAttr(), "warehouseName", FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            productSerialFlowEntity.setWarehouseId(productData.getLongValue(ReturnPurchaseProductEnum.WAREHOUSE.getAttr()));
            productSerialFlowEntity.setWarehouseName(productData.getString("warehouseName"));
            productSerialFlowEntity.setBusinessId(returnedPurchaseData.getLong(ReturnedPurchaseEnum.SUPPLIER_ID.getAttr()));
            productSerialFlowEntity.setBusinessName(returnedPurchaseData.getString(ReturnedPurchaseEnum.LINK_SUPPLIER_HIDE.getAttr()));
            productSerialFlowEntity.setSeqKey(seqKey);
            productSerialFlowEntity.setDel(BasicConstant.ZERO);

            seqKeyList.add(productSerialFlowEntity.getSeqKey());
            productSerialFlowEntityList.add(productSerialFlowEntity);
            productSerialFlowEntityMap.put(productSerialFlowEntity.getSeqKey(), productSerialFlowEntity);
        }

        if (CollectionUtils.isNotEmpty(productSerialFlowEntityList)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("seqKeyIn", seqKeyList);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            // 结存记录
            List<ProductSerialBalanceEntity> entitys = productSerialBalanceModel.findEntitys(param);
            for (ProductSerialBalanceEntity entity : entitys) {
                ProductSerialFlowEntity productSerialFlowEntity = productSerialFlowEntityMap.get(entity.getSeqKey());
                entity.setStatus(productSerialFlowEntity.getStatus());
                entity.setBusinessType(productSerialFlowEntity.getBusinessType());
                entity.setRefId(productSerialFlowEntity.getRefId());
                entity.setRefSheetNo(productSerialFlowEntity.getRefSheetNo());
                entity.setRefProductId(productSerialFlowEntity.getRefProductId());
                entity.setDate(productSerialFlowEntity.getDate());
                // 反向操作一波，仓库不变
                productSerialFlowEntity.setWarehouseId(entity.getWarehouseId());
            }
            // 新增流水
            productSerialFlowModel.insertBatch(productSerialFlowEntityList);
            // 更新结存
            productSerialBalanceModel.updateBatch(entitys, corpid);
        }
    }



    /**
     * 生成红冲付款单
     *
     * @param paySheetArray 选择关联的付款单
     * @param saasFormSaveDTO   保存入参
     * @throws XbbException 异常
     */
    public List<Long> generateRedPay(JSONArray paySheetArray, SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        List<Long> redPaySheetIds = new ArrayList<>();
        JSONObject newData = saasFormSaveDTO.getNewData();
        if (paySheetArray == null || paySheetArray.isEmpty() || newData == null) {
            return redPaySheetIds;
        }
        // 采购退货关联的回款单
        for(Object obj : paySheetArray) {
            JSONObject payJsonObject = (JSONObject) obj;
            PayPlanSheetEntityExt payPlanSheetEntityExt;
            payPlanSheetEntityExt = handlePaySheetWebPlatformLinkAddData(payJsonObject);
            FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
            BeanUtil.copyProperties(payPlanSheetEntityExt, formDataAddDTO);
            BeanUtil.copyProperties(saasFormSaveDTO, formDataAddDTO);
            JSONObject dataList = payPlanSheetEntityExt.getData();
            dataList.remove(PaySheetEnum.INVOICE_AMOUNT.getAttr());
            JSONObject paySheetTypeObj = FastJsonHelper.getJsonObjectOrDefaultFromFormData(dataList, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), new JSONObject());
            PaySheetTypeEnum paySheetTypeEnum = PaySheetTypeEnum.getByCode(paySheetTypeObj.getString("value"));
            JSONArray amountDetail = dataList.getJSONArray(PaasConstant.AMOUNTDETAIL);
            //金额中处理回款单类型从数组格式修正为数字形式
            if (amountDetail != null ) {
                amountDetail.forEach(e -> {
                    JSONObject jsonObject = (JSONObject) e;
                    if(jsonObject.get(PaySheetEnum.PAY_SHEET_TYPE.getAttr()) instanceof JSONObject){
                        JSONObject sonTypeObj = jsonObject.getJSONObject(PaySheetEnum.PAY_SHEET_TYPE.getAttr());
                        if(sonTypeObj != null && sonTypeObj.getString("value") != null){
                            jsonObject.put(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), sonTypeObj.getString("value"));
                        }
                    }
                });
            }
            if (Objects.equals(paySheetTypeEnum, PaySheetTypeEnum.WRITE_OFF_PAY)) {
                dataList.put(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.RED_WRITE_OFF_PAY.getCode());
                formDataAddDTO.setBusinessType(XbbRefTypeEnum.RED_WRITE_OFF_PAY.getCode());
                formDataAddDTO.setSubBusinessType(XbbRefTypeEnum.RED_WRITE_OFF_PAY.getCode());
            } else if (Objects.equals(paySheetTypeEnum, PaySheetTypeEnum.WRITE_OFF_PREPAY)) {
                dataList.put(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.RED_WRITE_OFF_PREPAY.getCode());
                formDataAddDTO.setBusinessType(XbbRefTypeEnum.RED_WRITE_OFF_PREPAY.getCode());
                formDataAddDTO.setSubBusinessType(XbbRefTypeEnum.RED_WRITE_OFF_PREPAY.getCode());
            } else {
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
            }
            formDataAddDTO.setDataList(dataList);
            formDataAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = new SaasNeedRedundantAttrPojo();
            saasNeedRedundantAttrPojo.setReturnedPurchaseId(saasFormSaveDTO.getNewPaasFormDataEntity().getId());
            formDataAddDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);
            JSONArray ownerJsonArray = payJsonObject.getJSONArray(FieldTypeEnum.OWNERID.getAlias());
            JSONArray coUserJsonArray = payJsonObject.getJSONArray(FieldTypeEnum.COUSERID.getAlias());
            List<ReturnUserAndDepartmentPojo> ownerId = new ArrayList<>();
            List<ReturnUserAndDepartmentPojo> coUserId = new ArrayList<>();
            if (Objects.nonNull(ownerJsonArray) && ownerJsonArray.size() > BasicConstant.ZERO) {
                ownerId = JSONArray.parseArray(ownerJsonArray.toJSONString(), ReturnUserAndDepartmentPojo.class);
            }
            if (Objects.nonNull(coUserJsonArray) && coUserJsonArray.size() > BasicConstant.ZERO) {
                coUserId = JSONArray.parseArray(coUserJsonArray.toJSONString(), ReturnUserAndDepartmentPojo.class);
            }
            formDataAddDTO.setOwnerId(ownerId);
            formDataAddDTO.setCoUserId(coUserId);
            formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            FormDataAddVO formDataAddVO = workflowOperatorDataService.add(formDataAddDTO);
            if (formDataAddVO.getDataId() != null) {
                redPaySheetIds.add(formDataAddVO.getDataId());
            }
        }
        return redPaySheetIds;
    }

    /**
     * 处理web端关联新建红冲付款单数据组装
     * @param payJsonObject web端返回新建付款单信息
     * @return 回款单实体
     * @author zhouwq
     * @date 2020/2/27 15:17
     */
    private PayPlanSheetEntityExt handlePaySheetWebPlatformLinkAddData(JSONObject payJsonObject){
        PayPlanSheetEntityExt payPlanSheetEntityExt = new PayPlanSheetEntityExt();
        if (payJsonObject == null) {
            return payPlanSheetEntityExt;
        }
        payPlanSheetEntityExt.setSerialNo(payJsonObject.getString(BasicConstant.SERIAL_NO));
        payPlanSheetEntityExt.setId(payJsonObject.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
        payPlanSheetEntityExt.setDataId(payJsonObject.getLong(StringConstant.DATA_ID));
        payPlanSheetEntityExt.setFormId(payJsonObject.getLong("formId"));
        payPlanSheetEntityExt.setMenuId(payJsonObject.getLong("menuId"));
        payPlanSheetEntityExt.setAppId(payJsonObject.getLong("appId"));
        payPlanSheetEntityExt.setAlone(payJsonObject.getInteger(FieldTypeEnum.SHEET_ALONE.getAlias()));
        payPlanSheetEntityExt.setUuid(payJsonObject.getString(FieldTypeEnum.SHEET_UUID.getAlias()));
        payPlanSheetEntityExt.setAddTime(payJsonObject.getLong("addTime"));
        payPlanSheetEntityExt.setUpdateTime(payJsonObject.getLong("updateTime"));
        payPlanSheetEntityExt.setOwnerId(payJsonObject.getString("ownerId"));
        payPlanSheetEntityExt.setFlowStatus(payJsonObject.getInteger("flowStatus"));
        payPlanSheetEntityExt.setDepartmentId(0L);
        payPlanSheetEntityExt.setDel(payJsonObject.getInteger("del"));
        payPlanSheetEntityExt.setCreatorId(payJsonObject.getString(StringConstant.CREATOR_ID));
        payJsonObject.remove("addTime");
        payJsonObject.remove("updateTime");
        payPlanSheetEntityExt.setData(payJsonObject);
        //删除创建人ID
        if (payJsonObject.get(StringConstant.CREATOR_ID) != null) {
            payJsonObject.remove(StringConstant.CREATOR_ID);
        }
        return payPlanSheetEntityExt;
    }



    public List<Long> saveReturnedPurchaseInvoice(SaasFormSaveDTO saasFormSaveDTO, JSONArray invoiceArray) throws XbbException {
        Long now = DateTimeUtil.getInt();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        String corpid = saasFormSaveDTO.getCorpid();
        Long returnedPurchaseId = newPaasFormDataEntity.getId();
        List<Long> invoiceIds = new ArrayList<>();
        if (Objects.isNull(invoiceArray)) {
            return invoiceIds;
        }
        //关联作废/红冲发票处理
        List<Long> cancelInvoiceIds = new ArrayList<>();
        for(Object obj : invoiceArray){
            JSONObject invoiceJsonObject = (JSONObject)obj;
            PaasFormDataEntity invoiceEntity = handleInvoiceWebPlatformLinkAddData(invoiceJsonObject);
            JSONObject invoiceData = invoiceEntity.getData();
            Integer isCancel = invoiceData.getInteger(PurchaseInvoiceEnum.IS_CANCEL.getAttr());
            Integer isRed = invoiceData.getInteger(PurchaseInvoiceEnum.IS_RED.getAttr());
            Long invoiceId = invoiceEntity.getId();
            if(Objects.equals(IsCancelEnum.IS_CANCEL.getCode(), isCancel)){
                cancelInvoiceIds.add(invoiceEntity.getId());
            }
            if(Objects.equals(IsRedEnum.RED.getCode(), isRed)){
                //关联红冲发票新建
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(invoiceEntity, formDataAddDTO);
                BeanUtil.copyProperties(saasFormSaveDTO, formDataAddDTO);
                JSONObject data = invoiceEntity.getData();
//                invoiceAmountDetailHandle(data);
                formDataAddDTO.setDataList(data);
                formDataAddDTO.setBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
                formDataAddDTO.setSubBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
                formDataAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = new SaasNeedRedundantAttrPojo();
                saasNeedRedundantAttrPojo.setReturnedPurchaseId(returnedPurchaseId);
                formDataAddDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);
                formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                FormDataAddVO formDataAddVO = workflowOperatorDataService.add(formDataAddDTO);
                //发票如果开启流程，返回的发票为空
                invoiceId = formDataAddVO.getDataId();
            }
            if (invoiceId != null) {
                ReturnedPurchaseInvoiceEntity returnedPurchaseInvoiceEntity = new ReturnedPurchaseInvoiceEntity();
                returnedPurchaseInvoiceEntity.setReturnedPurchaseId(returnedPurchaseId);
                returnedPurchaseInvoiceEntity.setCorpid(corpid);
                returnedPurchaseInvoiceEntity.setDel(DelEnum.NORMAL.getDel());
                returnedPurchaseInvoiceEntity.setAddTime(now);
                returnedPurchaseInvoiceEntity.setUpdateTime(now);
                returnedPurchaseInvoiceEntity.setInvoiceId(invoiceId);
                returnedPurchaseInvoiceModel.save(returnedPurchaseInvoiceEntity);
                invoiceIds.add(invoiceId);
            }
        }
        // 关联作废发票
        if (!cancelInvoiceIds.isEmpty()) {
            CancelDTO cancelDTO = new CancelDTO();
            BeanUtil.copyProperties(saasFormSaveDTO, cancelDTO);
            cancelDTO.setSingle(0);
            cancelDTO.setStatus(1);
            cancelDTO.setBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
            cancelDTO.setDataIdList(cancelInvoiceIds);
            cancelDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            listBatchService.cancel(cancelDTO);
        }
        return invoiceIds;
    }


    private PaasFormDataEntity handleInvoiceWebPlatformLinkAddData(JSONObject paymentJsonObject){
        PaasFormDataEntity paasFormDataEntity = new PaymentSheetEntityExt();
        paasFormDataEntity.setSerialNo(paymentJsonObject.getString(PaymentSheetEnum.SHEET_NO.getAttr()));
        paasFormDataEntity.setId(paymentJsonObject.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
        paasFormDataEntity.setDataId(paymentJsonObject.getLong(StringConstant.DATA_ID));
        paasFormDataEntity.setFormId(paymentJsonObject.getLong("formId"));
        paasFormDataEntity.setMenuId(paymentJsonObject.getLong("menuId"));
        paasFormDataEntity.setAppId(paymentJsonObject.getLong("appId"));
        paasFormDataEntity.setAddTime(paymentJsonObject.getLong("addTime"));
        paasFormDataEntity.setUpdateTime(paymentJsonObject.getLong("updateTime"));
        paasFormDataEntity.setOwnerId(paymentJsonObject.getString("ownerId"));
        paasFormDataEntity.setFlowStatus(paymentJsonObject.getInteger("flowStatus"));
        paasFormDataEntity.setDepartmentId(0L);
        paasFormDataEntity.setDel(paymentJsonObject.getInteger("del"));
        paasFormDataEntity.setCreatorId(paymentJsonObject.getString("creatorId"));
        paymentJsonObject.remove("addTime");
        paymentJsonObject.remove("updateTime");
        paasFormDataEntity.setData(paymentJsonObject);
        return paasFormDataEntity;
    }

}
